import React, { useContext, useState, useMemo } from 'react'
import Myback from '../components/Myback'
import { Tabs, ProductCard, Tag, Button, Space } from 'react-vant'
import Ctx from '../store/Ctx'
import type { dataTs } from '../store/storeTs'
import { Star } from '@react-vant/icons';
import type { RouteComponentProps } from 'react-router-dom'

export default function Home(props: RouteComponentProps) {

  //上下文获取数据
  let obj = useContext(Ctx)

  let [index, setIndex] = useState<number>(0) //0全部 1推荐 2小说 3儿童

  //当切换的时候 == index发生变化
  let newlist = useMemo(() => {
    return obj.datalist.filter((item: dataTs) => {
      if (index == 0) {
        return item
      }
      return item.typeId == index
    })
  }, [obj.datalist, index])

  return (
    <div>
      {/* 导航栏 */}
      <Myback title={'首页'} leftText={false}></Myback>

      {/* 标签页 */}
      <Tabs color='red' onChange={(e) => {
        setIndex(e as number)
      }}>
        {['全部', '推荐', '小说', '儿童'].map(item => (
          <Tabs.TabPane key={item} title={item}></Tabs.TabPane>
        ))}
      </Tabs>

      {/* 商品卡片 渲染数据 */}
      <div style={{ height: 'calc(100vh - 150px)', overflowY: 'scroll' }}>
        {
          newlist.map((item: dataTs) => {
            return <ProductCard onClick={() => {
              //跳转到详情页
              props.history.push({
                pathname: '/details',
                state: item.id
              })
            }}
              num={<Space>
                <span onClick={(e) => {
                  //阻止事件冒泡
                  e.stopPropagation()
                  //收藏
                  obj.dispatch({
                    type: 'change_collect',
                    payload: item.id
                  })
                }}>
                  <Star color={item.collect ? 'red' : '#999'} />
                </span>
                <Button size='mini' round
                  type={item.sub ? 'warning' : 'default'}
                  onClick={(e) => {
                    //阻止事件冒泡
                    e.stopPropagation()
                    //订阅状态切换
                    obj.dispatch({
                      type: 'change_sub',
                      payload: item.id
                    })
                  }}>
                  {item.sub ? '已经订阅' : '免费订阅'}
                </Button>
              </Space>}
              key={item.id}
              desc={item.ms}
              title={item.title}
              thumb={item.img}
            />
          })
        }

      </div>

    </div>
  )
}           
